package com.oceanstar.mapper;

import com.baomidou.mybatisplus.core.mapper.Mapper;
import com.oceanstar.Pojo.ElderBindingInfo;
import com.oceanstar.Pojo.UserInfo;
import org.apache.ibatis.annotations.*;

import java.util.List;

public interface UserInfoMapper extends Mapper<UserInfo> {

    // 修改插入方法，避免与MyBatis Plus的insert方法冲突
    @Insert("INSERT INTO userinfo_table (name, phone, id_card, identity, emergency_id, " +
            "password, address, create_time, update_time) " +
            "VALUES (#{name}, #{phone}, #{idCard}, #{identity}, #{emergencyId}, " +
            "#{password}, #{address}, #{createTime}, #{updateTime})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void insertUser(UserInfo userInfo);

    // 登录查询（保持不变）
    @Select("SELECT * FROM userinfo_table WHERE phone = #{phone} AND password = #{password}")
    UserInfo selectByUsernameAndPassword(UserInfo userInfo);

    // 获取用户列表（新增注解）
    List<UserInfo> selectUserList(
            @Param("userInfo") UserInfo userInfo,
            @Param("offset") Integer offset,
            @Param("pageSize") Integer pageSize
    );

    // 获取用户列表数量（新增注解）
    Long countUserList(@Param("userInfo") UserInfo userInfo);

    // 删除用户（新增注解）
    void deleteUsers(@Param("ids") Number[] ids);

    // 通过电话号码查询用户（保持不变）
    @Select("SELECT * FROM userinfo_table WHERE phone = #{phone}")
    UserInfo selectByPhone(@Param("phone") String phone);

    // 通过id查询用户（新增注解）
    UserInfo selectById(@Param("id") Number id);

    // 更新用户信息（新增注解）
    void updateUsers(@Param("userInfo") UserInfo userInfo);

    // 管理员更新用户信息（新增注解）
    void updateUsersByAdmin(@Param("userInfo") UserInfo userInfo);

    // 获取所有用户信息（新增注解）
    @Select("SELECT * FROM userinfo_table")
    List<UserInfo> getAllUsers();

    // 最后登录时间更新（保持不变）
    @Update("UPDATE userinfo_table SET update_time = now() WHERE id = #{id}")
    void updateLastLoginTime(@Param("id") Number id);

    // 查询用户积分（保持不变）
    @Select("SELECT points FROM userinfo_table WHERE id = #{userId}")
    Integer selectUserPointsById(@Param("userId") Number id);

    // 更新用户积分（保持不变）
    @Update("UPDATE userinfo_table SET points = #{newPoints} WHERE id = #{userId}")
    int updateUserPointsById(@Param("userId") Number userId, @Param("newPoints") Integer newPoints);

    // 家属绑定老人（新增注解）
    @Update("UPDATE userinfo_table SET " +
            "relation = #{bindFamily.relation}, " +
            "bindId = #{bindFamily.bindId}, " +
            "bindTime = #{bindFamily.bindTime} " +
            "WHERE id = #{id}")
    void updateBindFamilyById(@Param("id") Integer id, @Param("bindFamily") UserInfo bindFamily);

    // 查询绑定到指定老人的所有家属
    @Select("SELECT * FROM userinfo_table WHERE bindId = #{elderId} AND identity = 2")
    List<UserInfo> selectFamiliesByElderId(@Param("elderId") Integer elderId);

    @Update("UPDATE userinfo_table SET gridId = #{gridId}, bindDate = #{bindDate}, update_time = NOW() WHERE id = #{elderId}")
    int assignElderToGrid(@Param("elderId") Integer elderId, @Param("gridId") Integer gridId, @Param("bindDate") String bindDate);

    //老人解绑网格员
    @Update("UPDATE userinfo_table SET gridId = NULL, bindDate = #{bindDate}, update_time = NOW() WHERE id = #{elderId}")
    int unassignElder(@Param("elderId") Integer elderId, @Param("bindDate") String bindDate);

    // 统计网格员绑定的老人数量
    @Select("SELECT COUNT(*) FROM userinfo_table " +
            "WHERE gridId = #{gridId} " +
            "AND (#{name} IS NULL OR #{name} = '' OR name LIKE CONCAT('%', #{name}, '%'))")
    Long countGridBindings(@Param("gridId") Integer gridId, @Param("name") String name);

    // 查询网格员绑定的老人列表（分页+筛选）
    @Select("SELECT " +
            "id as elderlyId, name, gender, " +
            "TIMESTAMPDIFF(YEAR, id_card, CURDATE()) as age, " +
            "address, phone, bindDate " +
            "FROM userinfo_table " +
            "WHERE gridId = #{gridId} " +
            "AND (#{name} IS NULL OR #{name} = '' OR name LIKE CONCAT('%', #{name}, '%')) " +
            "ORDER BY bindDate DESC " +
            "LIMIT #{offset}, #{pageSize}")
    List<ElderBindingInfo> selectGridBindings(@Param("gridId") Integer gridId,
                                              @Param("offset") Integer offset,
                                              @Param("pageSize") Integer pageSize,
                                              @Param("name") String name);
}